package com.genius.reservation.common.GlobalExceptionHandler;

import com.alibaba.fastjson.JSONObject;
import com.genius.reservation.common.ResponseRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.sql.SQLNonTransientException;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(value = SQLNonTransientException.class)
    @ResponseBody
    public ResponseRule Exce(HttpServletRequest req,Exception e) throws Exception{
        logger.error("捕获到SQL异常{}   ,发生路径{}   ,参数{}",e.getMessage(),req.getRequestURI(), JSONObject.toJSON(req.getParameterNames()));
        return ResponseRule.no("出错了,请稍后再试");
    }
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResponseRule NullExce(HttpServletRequest req,Exception e) throws Exception{

        logger.error("捕获到NullPointer异常   ,发生路径{}   ,参数{}", req.getRequestURI(),JSONObject.toJSON(req.getParameterNames()));
        e.printStackTrace();
        return ResponseRule.no("出错了,请稍后再试");
    }
    @ExceptionHandler(value = SQLException.class)
    @ResponseBody
    public ResponseRule SQLExce(HttpServletRequest req,Exception e) throws Exception{
        logger.error("捕获到SQL异常{}   ,发生路径{}   ,参数{}",e.getMessage(),req.getRequestURI(),JSONObject.toJSON(req.getParameterNames()));
        return ResponseRule.no("出错了,请稍后再试");
    }
    @ExceptionHandler(value = GlobalException.class)
    @ResponseBody
    public ResponseRule GlobExce(HttpServletRequest req,GlobalException e) throws Exception{
        logger.error("捕获到Glob异常{}  ,发生路径{}   ,参数{}",e.getMessage(),req.getRequestURI(),JSONObject.toJSON(req.getParameterNames()));
        return ResponseRule.no("出错了,请稍后再试");
    }

//    @ExceptionHandler(value = TokenException.class)
//    @ResponseBody
//    public ResponseRule TokenExce(HttpServletRequest req,TokenException e) throws Exception{
//        logger.error("捕获到Token异常{}  ,发生路径{}   ,参数{}",e.getMessage(),req.getRequestURI(),JSONObject.toJSON(req.getParameterNames()));
//        return ResponseRule.no("TOKEN失效,请重新登录");
//    }

    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    @ResponseBody
    public ResponseRule parExcepton(HttpServletRequest req,MissingServletRequestParameterException e) throws Exception{
        logger.error("捕获到Parameter异常{}  ,发生路径{} ,参数{} ",e.getMessage(),req.getRequestURI(),JSONObject.toJSON(req.getReader()));
//        System.out.println(req);
        return ResponseRule.no("请填写正确参数");
    }

}
